package com.atguigu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableAspectJAutoProxy
public class RedisConfig {
    /** Redis服务器只能存储字符串和字节数组等基本数据类型* Java应用需要存储复杂对象，需要通过序列化将其转换为Redis可识别的格式
     * 创建并配置RedisTemplate实例
     *
     * @param factory Redis连接工厂，用于创建Redis连接
     * @return 配置好的RedisTemplate实例，用于执行Redis操作
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setEnableTransactionSupport(true);// 启用Redis事务支持，开启后可以在Redis操作中使用事务

        // 配置序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();


        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);

        // 初始化RedisTemplate实例，设置序列化器、连接工厂等属性
        // 该方法在RedisTemplate的所有属性设置完成后调用，确保模板能够正常工作
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }


}
